<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								客户表
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- 							<el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar :style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<div class="static-content-item">
							<div>基本信息</div>
						</div>
						<!--  -->
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="客户名称" prop="customerName">
									<el-input v-model="formData.customerName" type="text" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="客户分级" prop="customerRating">
									<el-select @clear="selectClear('customerRating')" v-model="formData.customerRating"
										@change="(value:any)=>selectChange(value,'customerRating')" multiple
										ref="customerRating" clearable>
										<el-option v-for="(item, key) in customerRatingOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<el-tag style="border: 0;" :color="item?.color" round effect="dark">
												{{ item?.label }}
											</el-tag>
											<!--  -->
										</el-option>
										<!--  -->
										<template #tag>
											<el-tag style="border: 0;" v-if="customerRatingOption[ratingIndex]?.value"
												:color="customerRatingOption[ratingIndex]?.color" round effect="dark">
												{{ customerRatingOption[ratingIndex]?.label }}
											</el-tag>
										</template>
									</el-select>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<el-form-item label="客户来源" prop="customerSource">
							<el-select @clear="selectClear('customerSource')" v-model="formData.customerSource"
								@change="(value:any)=>selectChange(value,'customerSource')" multiple
								ref="customerSource" clearable>
								<el-option v-for="(item, key) in customerSourceOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<el-tag style="border: 0;" :color="item?.color" round effect="dark">
										{{ item?.label }}
									</el-tag>
									<!--  -->
								</el-option>
								<!--  -->
								<template #tag>
									<el-tag style="border: 0;" v-if="customerSourceOption[sourceIndex]?.value"
										:color="customerSourceOption[sourceIndex]?.color" round effect="dark">
										{{ customerSourceOption[sourceIndex]?.label }}
									</el-tag>
								</template>
							</el-select>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="客户联系电话" prop="customerPhone">
									<el-input v-model="formData.customerPhone" type="text" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="客户联系人" prop="customerContact">
									<el-input v-model="formData.customerContact" type="text" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<el-form-item label="获客时间" prop="acquisitionTime">
							<el-date-picker style="width:100%;" v-model="formData.acquisitionTime" type="date" />
						</el-form-item>
						<el-form-item label="负责销售" prop="salesRepresentative">
							<el-input v-model="formData.salesRepresentative" type="text" clearable></el-input>
						</el-form-item>
						<div class="static-content-item">
							<div>地址信息</div>
						</div>
						<el-form-item label="详细地址" prop="address">
							<el-input v-model="formData.address" type="text" clearable></el-input>
						</el-form-item>
						<div class="static-content-item">
							<div>开票信息</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="开票单位" prop="billingEntity">
									<el-input v-model="formData.billingEntity" type="text" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="纳税人识别号" prop="taxpayerId">
									<el-input v-model="formData.taxpayerId" type="text" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>结算信息</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="8">
								<!--  -->
								<el-form-item label="结算方式" prop="billingMethod">
									<el-input v-model="formData.billingMethod" readonly type="text" clearable
										class="my">
										<template #prefix>
											<div>
												<el-check-tag
													:style="`color: ${billingMethodIndex===key?'#fff':''};${billingMethodIndex===key?`background: ${item.bg}`:''}`"
													v-for="(item,key) in billingMethodOption" :key="key"
													:checked="billingMethodIndex===key"
													@change="tagChange(key)">{{item.text}}</el-check-tag>
											</div>
										</template>
									</el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="8">
								<!--  -->
								<el-form-item label="开户行" prop="bankName">
									<el-input v-model="formData.bankName" type="text" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="8">
								<!--  -->
								<el-form-item label="银行账号" prop="bankAccount">
									<el-input v-model="formData.bankAccount" type="text" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<!--  -->
						<el-row :gutter="16" v-show="billingMethodIndex===1">
							<el-col :span="8">
								<!--  -->
								<el-form-item label="对账周期" prop="reconciliation">
									<el-input v-model="formData.reconciliation" type="text" clearable>
										<template #suffix>
											<e-text>天</e-text>
										</template>
									</el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="8">
								<!--  -->
								<el-form-item label="上次对账日" prop="startTime">
									<el-date-picker style="width:100%;" v-model="formData.startTime" type="date" />
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="8">
								<!--  -->
								<el-form-item label="下次对账日" prop="endTime">
									<el-input v-model="formData.endTime" type="text" disabled placeholder="保存后显示计算结果"
										clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<!--  -->
						<div class="static-content-item">
							<div>回款&开票</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="销售总额" prop="totalSales">
									<el-input v-model="formData.totalSales" type="text" disabled placeholder="保存后显示计算结果"
										clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="应收总额" prop="totalReceivables">
									<el-input v-model="formData.totalReceivables" type="text" disabled
										placeholder="保存后显示计算结果" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<!--  -->
						<el-row :gutter="16">
							<el-col :span="8">
								<!--  -->
								<el-form-item label="已收金额" prop="receivedAmount">
									<el-input v-model="formData.receivedAmount" type="text" disabled
										placeholder="保存后显示计算结果" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="8">
								<!--  -->
								<el-form-item label="待回款金额" prop="pendingCollectionAmount">
									<el-input v-model="formData.pendingCollectionAmount" type="text" disabled
										placeholder="保存后显示计算结果" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="8">
								<!--  -->
								<el-form-item label="退款金额" prop="refundAmount">
									<el-input v-model="formData.refundAmount" type="text" disabled
										placeholder="保存后显示计算结果" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<!--  -->
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="已开票金额" prop="invoicedAmount">
									<el-input v-model="formData.invoicedAmount" type="text" disabled
										placeholder="保存后显示计算结果" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="待开票金额" prop="pendingInvoicingAmount">
									<el-input v-model="formData.pendingInvoicingAmount" type="text" disabled
										placeholder="保存后显示计算结果" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { ref, onMounted, reactive } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import { ArrowDown } from '@element-plus/icons-vue';
	import request from '../../../utils/request';
	import { ElMessage, FormInstance } from 'element-plus';
	import { colors, findIndexByLabel, isEmpty } from '../../../utils/index';
	import { formatDate } from '../../../utils/date';
	const emits = defineEmits(['update']);
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	// 表单
	const formData = ref({
		customerId: '',
		customerName: '',
		customerRating: [],
		customerRatingId: 0,
		customerSource: [],
		customerSourceId: 0,
		customerPhone: '',
		customerContact: '',
		acquisitionTime: '',
		salesRepresentative: '',
		address: '',
		billingEntity: '',
		taxpayerId: '',
		billingMethod: '',
		billingMethodId: 0,
		bankName: '',
		bankAccount: '',
		reconciliation: '',
		startTime: '',
		endTime: '',
		totalSales: '',
		totalReceivables: '',
		receivedAmount: '',
		pendingCollectionAmount: '',
		refundAmount: '',
		invoicedAmount: '',
		pendingInvoicingAmount: '',
	});
	//
	const customerRatingOption = ref([]);
	const customerSourceOption = ref([]);
	const billingMethodOption = ref([]);
	//
	const rules = reactive({
		customerName: [{ required: true, message: '客户名称必填！', trigger: ['blur', 'change'] }],
		customerRating: [],
		customerSource: [{ required: true, message: '客户来源必填！', trigger: ['blur', 'change'] }],
		customerPhone: [],
		customerContact: [],
		acquisitionTime: [{ required: true, message: '获客时间必填！', trigger: ['blur', 'change'] }],
		salesRepresentative: [],
		address: [],
		billingEntity: [],
		billingMethod: [{ required: true, message: '结算方式必填！', trigger: ['blur', 'change'] }],
		bankName: [],
		bankAccount: [],
		reconciliation: [],
		startTime: [],
		endTime: [],
		totalSales: [],
		totalReceivables: [],
		receivedAmount: [],
		pendingCollectionAmount: [],
		refundAmount: [],
		invoicedAmount: [],
		pendingInvoicingAmount: [],
	});
	//
	onMounted(() => {
		// getCustomer();
	});
	//
	const tagChange = (index : number) => {
		if (billingMethodIndex.value === index) {
			billingMethodIndex.value = -1;
			return;
		}
		billingMethodIndex.value = index;
		//set id
		formData.value.billingMethodId = billingMethodOption.value[index].value;
		formData.value.billingMethod = billingMethodOption.value[index].value;
	}
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getCustomer();
			//
			if (result) {
				getDict();
				getCustomerSource();
				getCustomerMethod();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		ratingIndex.value = -1;
		sourceIndex.value = -1;
		billingMethodIndex.value = -1;
		//清空url参数
		router.push({ query: {} });
	}
	//客户等级
	const getDict = async () => {
		const result = await request({
			url: '/login/selectDict',
			params: {},
		});
		//
		console.log('getDict--->', result);
		customerRatingOption.value = [];
		const options = result.data.t;
		options.forEach((item : any) => {
			customerRatingOption.value.push({
				label: item?.customerRating,
				color: colors(item?.customerRating, 'grading'),
				value: item?.id
			});
		});
		//
		customerRatingOption.value.forEach((item) => {
			// console.log('formData.customerRatingId == item.value--->', formData.value.customerRatingId, item.value);
			if (formData.value.customerRatingId === item?.value) {
				formData.value.customerRating = [item?.value];
				//
				const index = findIndexByLabel(customerRatingOption.value, item?.value, 'value');
				// console.log('index--->',index);
				ratingIndex.value = index;
			}
		});
		//
		console.log('customerRatingOption--->', customerRatingOption.value);
	}
	//客户来源
	const getCustomerSource = async () => {
		const result = await request({
			url: '/login/selectCustomerSource',
			params: {},
		});
		//
		console.log('getCustomerSource--->', result);
		customerSourceOption.value = [];
		const options = result.data.t;
		options.forEach((item : any) => {
			customerSourceOption.value.push({
				label: item?.customerSource,
				color: '#86a3bf',
				value: item?.id
			});
		});
		//
		customerSourceOption.value.forEach((item) => {
			// console.log('formData.customerRatingId == item.value--->', formData.value.customerRatingId, item.value);
			if (formData.value.customerSourceId === item?.value) {
				formData.value.customerSource = [item?.value];
				//
				const index = findIndexByLabel(customerSourceOption.value, item?.value, 'value');
				// console.log('index--->',index);
				sourceIndex.value = index;
			}
		});
	}
	//核销方式
	const getCustomerMethod = async () => {
		const result = await request({
			url: '/login/selectCustomerMethod',
			params: {},
		});
		//
		console.log('getCustomerMethod--->', result);
		//
		billingMethodOption.value = [];
		const options = result.data.t;
		options.forEach((item : any) => {
			billingMethodOption.value.push({
				text: item?.billingMethod,
				bg: colors(item?.billingMethod, 'manner'),
				value: item?.id
			});
		});
		//
		billingMethodOption.value.forEach((item, key) => {
			if (formData.value.billingMethodId === item.value) {
				formData.value.billingMethod = item.value;
				billingMethodIndex.value = key;
			}
		})
	}
	//
	const getCustomer = async () => {
		if (!route.query.id) return true;
		const result = await request({
			url: '/login/selectCustomer',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getCustomer--->', result);
		//
		formData.value = result.data.t;
		formData.value.acquisitionTime = formatDate(formData.value.acquisitionTime);
		formData.value.endTime = formatDate(formData.value.endTime);
		return true;
	}
	//
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	//
	const customerRating = ref(null);
	const customerSource = ref(null);
	//
	const ratingIndex = ref(-1);
	const sourceIndex = ref(-1);
	const billingMethodIndex = ref(-1);
	//改变
	const selectChange = (value : Array<any>, type : string) => {
		//
		// console.log('selectChange--->', value);
		formData.value[type] = [];
		let value1 = [value[value.length - 1]];
		// console.log('value1--->',value1);
		if (isEmpty(value1[0])) {
			value1 = [];
		} else {
			value1 = [value1[0]];
		}
		formData.value[type] = value1;
		//
		if (type === 'customerRating') {
			const index = findIndexByLabel(customerRatingOption.value, value1[0], 'value');
			// console.log('index--->',index);
			ratingIndex.value = index;
			//set id
			formData.value.customerRatingId = value1[0];
			//
			customerRating.value.blur();
		}
		if (type === 'customerSource') {
			const index = findIndexByLabel(customerSourceOption.value, value1[0], 'value');
			// console.log('index--->',index);
			sourceIndex.value = index;
			//set id
			formData.value.customerSourceId = value1[0];
			//
			customerSource.value.blur();
		}
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				let type = '';
				if (!route.query.id) {
					type = '/saveCustomer';
				} else {
					type = '/updateCustomer';
				}
				const data = formData.value;
				delete data.billingMethod;
				delete data.customerRating;
				delete data.customerSource;
				//
				const result = await request({
					url: '/login' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				//
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	defineExpose({
		openDialog
	})
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>